/*
 * create by 陈云亮(shiny_vc@163.com)
 */
ckez.CKeditor = zk.$extends(zk.Widget, {
    _value: '',
    _type: 'classic',
    _disabled: false,
    _uploadUrl: null,
    _placeholder: null,
    _toolbar: null,
    _focus: false,
    _editor: null,
    _fireFlag: true,//用作没有焦点时抛出数据

    $define: {

        disabled: function (v) {
            if (this._editor)
                this._editor.isReadOnly = this._disabled;
        },
        value: function (v) {
            if (this._editor)
                this._editor.setData(v);
        },
        toolbar: _zkf = function () {
            if (this.desktop)
                this.rerender();
        },
        placeholder: _zkf,
        type: _zkf,
        uploadUrl: _zkf,
        width: function (v) {
            if (!v || !this.$n())
                return;
            this._setSize(v, 'width');
        },
        height: function (v) {
            if (!v || !this.$n())
                return;
            this._setSize(v, 'height');
        }
    },
    setVflex: function (v) {
        if (v == 'min')
            v = false;
        if (this._editor)
            this.$super(ckez.CKeditor, 'setVflex', v);
        else
            this._tmpVflex = v;
    },
    setHflex: function (v) {
        if (v == 'min')
            v = false;
        if (this._editor)
            this.$super(ckez.CKeditor, 'setHflex', v);
        else
            this._tmpHflex = v;
    },
    setFlexSize_: function (sz, ignoreMargins) {
        if (this._editor) {
            var n = this.$n(), zkn = zk(n);
            if (sz.height !== undefined) {
                if (sz.height == 'auto')
                    n.style.height = '';
                else if (sz.height != '')
                    this.setFlexSizeH_(n, zkn, sz.height - 35, ignoreMargins);
                else {
                    n.style.height = this._height || '';
                    if (this._height)
                        this._setSize(this._height, 'height');
                    else
                        this._setSize('200px', 'height');
                }
            }
            if (sz.width !== undefined) {
                if (sz.width == 'auto')
                    n.style.width = '';
                else if (sz.width != '')
                    this.setFlexSizeW_(n, zkn, sz.width - 35, ignoreMargins);
                else {
                    n.style.width = this._width || '';
                    if (this._width)
                        this._setSize(this._width, 'width');
                    else
                        this._setSize('100%', 'width');
                }
            }
            return {
                height: n.offsetHeight,
                width: n.offsetWidth
            };
        }
    },
    setFlexSizeH_: function (n, zkn, height, ignoreMargins) {
        this._hflexHeight = height;
        this.$super(ckez.CKeditor, 'setFlexSizeH_', n, zkn, height,
            ignoreMargins);
        var h = parseInt(n.style.height);
        n.style.height = '';
        this._setSize(jq.px0(h), 'height');
    },
    setFlexSizeW_: function (n, zkn, width, ignoreMargins) {
        this.$super(ckez.CKeditor, 'setFlexSizeW_', n, zkn, width,
            ignoreMargins);
        var w = parseInt(n.style.width);
        this._setSize(jq.px0(w), 'width');
    },
    _setSize: function (value, prop) {
        value = this._getValue(value);
        if (!value)
            return;
        var wgt = this;
        this._editor.editing.view.change(function (writer) {
            if (prop == 'width')
                writer.setStyle('width', value, wgt._editor.editing.view.document.getRoot());
            else
                writer.setStyle('height', value, wgt._editor.editing.view.document.getRoot());
        });
    },
    _getValue: function (value) {
        if (!value)
            return null;
        if (value.endsWith('%'))
            return zk.ie ? jq.px0(jq(this.$n()).width()) : value;
        return jq.px0(zk.parseInt(value));
    },
    domAttrs_: function (no) {
        var attr = this.$supers('domAttrs_', arguments);
        if (!this.isVisible() && (!no || !no.visible))
            attr += ' style="display:none;"';
        return attr;
    },
    bind_: function () {
        this.$supers('bind_', arguments);
        var wgt = this;
        setTimeout(function () {
            wgt._init()
        }, 50);
    },
    unbind_: function () {
        if (!this._editor) {
            this._unbind = true;
            this._arguments = arguments;
            return;
        }
        try {
            this._editor.destroy();
            this._editor = null;
        } catch (e) {
        }
        this._unbind = this._editor = this._tmpVflex = this._tmpHflex = null;
        this.$supers('unbind_', arguments);
    },
    focus: function () {
        if (this._editor)
            this._editor.editing.view.focus();
    },
    _init: function () {
        var wgt = this, uuid = this.uuid,
            dtid = this.desktop.id, editClass, lang = navigator.language.toLowerCase(), config = {
                removePlugins: []
            };
        if (this._placeholder)
            config.placeholder = this._placeholder;
        if (this._toolbar === 'basic') {
            config.removePlugins.push('PageBreak');
            config.removePlugins.push('Underline');
            config.removePlugins.push('Strikethrough');
            config.removePlugins.push('Code');
            config.removePlugins.push('Subscript');
            config.removePlugins.push('Superscript');
            config.removePlugins.push('TodoList');
            config.removePlugins.push('Indent');
            config.removePlugins.push('Highlight');
            config.removePlugins.push('Alignment');
            config.toolbar = [
                'heading',
                '|',
                'bold',
                'italic',
                'link',
                'bulletedList',
                'numberedList',
                'imageUpload',
                'imageViaUrlEmbed',
                'blockQuote',
                'insertTable',
                'mediaEmbed',
                'undo',
                'redo'
            ]
        } else if (this._toolbar === 'medium') {
            config.toolbar = [
                'heading',
                '|',
                'fontSize',
                'fontFamily',
                'fontColor',
                'fontBackgroundColor',
                '|',
                'bold',
                'italic',
                'underline',
                'strikethrough',
                'code',
                '|',
                'link',
                'bulletedList',
                'numberedList',
                '|',
                'imageUpload',
                'blockQuote',
                'insertTable',
                'mediaEmbed',
                '|',
                'undo',
                'redo'
            ]
        } else if (this._toolbar === 'full') {

        } else if (this._toolbar)
            config.toolbar = this._toolbar.split(',');

        if (this._uploadUrl) {

            config.removePlugins.push('Base64UploadAdapter');
            config.simpleUpload = {
                uploadUrl: wgt._uploadUrl + '?&dtid=' + dtid + '&uuid=' + uuid
            }
        } else
            config.removePlugins.push('SimpleUploadAdapter');
        if (this._type === 'block') {
            editClass = "BalloonEditor";
        } else {
            config.removePlugins.push('BlockToolbar');
            if (this._type === 'classic') {
                editClass = "ClassicEditor";
            } else if (this._type === 'document')
                editClass = "DocumentEditor";
            else if (this._type === 'inline')
                editClass = "InlineEditor";
            else
                editClass = "BalloonEditor";
        }
        //config = zk.$default(config, CKEDITOR.ClassicEditor.defaultConfig);
        if (lang === 'zh-cn') {
            zk.override(config, {}, {
                fontFamily: {
                    options: [
                        'Default',
                        '宋体',
                        '黑体',
                        '楷体',
                        '微软雅黑'
                    ]
                }
            });
        } else if (lang === 'zh-tw')
            config.language = 'zh';
        else config.language = 'en';

        CKEDITOR[editClass].create(document.querySelector('#' + this.uuid + '-editor'), config).then(function (editor) {
            if (wgt._type === 'document') {
                var toolbarContainer = document.querySelector('#' + wgt.uuid + '-toolbar');
                toolbarContainer.appendChild(editor.ui.view.toolbar.element);
            }
            editor.isReadOnly = wgt._disabled;
            if (wgt.isListen('onChanging')) {
                editor.model.document.on('change', function () {
                    if (editor.model.document.differ.getChanges().length > 0)
                        wgt.fire('onChanging', {value: editor.getData()});
                });
            }

            //用作编辑器未获取焦点时,内容改变即抛出数据，当获取焦点时，该方法即不执行
            editor.model.document.on('change:data', function () {
                if (wgt._fireFlag === true) {
                    var val = editor.getData();
                    if (wgt._value !== val) {
                        setTimeout(function () {
                            wgt.fire('onChange', {value: val});
                        }, 0);
                        wgt._value = val;
                    }
                }
            });

            editor.editing.view.document.on('change:isFocused', function (evt, name, isFocused) {
                wgt._fireFlag = false
                var val = editor.getData();
                if (!isFocused && wgt._value !== val) {//当blur发生时触发onChange事件
                    setTimeout(function () {
                        wgt.fire('onChange', {value: val});
                    }, 0);
                    wgt._value = val;
                }
            });
            editor.setData(wgt._value);
            wgt._value = editor.getData();
            wgt._editor = editor;
            if (wgt._height) {
                editor.editing.view.change(function (writer) {
                    writer.setStyle('height', wgt._height, editor.editing.view.document.getRoot());
                });
            }
            if (wgt._width) {
                editor.editing.view.change(function (writer) {
                    writer.setStyle('width', wgt._width, editor.editing.view.document.getRoot());
                });
            }
            if (!wgt._tmpHflex && wgt._hflex) {
                wgt._tmpHflex = wgt._hflex;
                wgt.setHflex(null);
            }
            if (!wgt._tmpVflex && wgt._vflex) {
                wgt._tmpVflex = wgt._vflex;
                wgt.setVflex(null);
            }
            if (wgt._tmpHflex) {
                wgt.setHflex(wgt._tmpHflex, {
                    force: true
                });
                wgt._tmpHflex = null;
            }
            if (wgt._tmpVflex) {
                wgt.setVflex(wgt._tmpVflex, {
                    force: true
                });
                wgt._tmpVflex = null;
            }
        }).catch(function (error) {
            console.log(error);
        });
    }
});